package com.itheima.admin.listener;

import com.itheima.admin.service.WemediaNewsAutoScanService;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.admin.listener
 */
@Component
@Slf4j
public class WemediaNewsAutoScanListener {

    @Resource
    private WemediaNewsAutoScanService wemediaNewsAutoScanService;

    /**
     * 监听自媒体文章的自动审核
     * @param msg
     */
    @KafkaListener(topics = BusinessConstants.MqConstants.WM_NEWS_AUTO_SCAN_TOPIC)
    public void consumerMsg(ConsumerRecord<String,String> msg){
        int p = msg.partition();
        long o = msg.offset();
        String wmNewsIdStr = msg.value();
        // 作为log日志的唯一标记
        String uuid = UUID.randomUUID().toString();
        log.info("自媒体文章的自动审核 开始...{},{},{},{}", uuid,p,o,wmNewsIdStr);
        long wmNewsId = Long.parseLong(wmNewsIdStr);
        try {
            // 审核处理
            wemediaNewsAutoScanService.autoScanWemediaNewsById(wmNewsId, uuid);
        } catch (Exception e) {
            log.error("自媒体文章的自动审核 出异常了, uuid={}", uuid, e);
            // 使用RabbitMQ, 抛异常 消费者失败，重试机制，耗尽时，进入死信，由运维人员来处理
            throw new LeadNewsException(String.format("文章自动审核失败!uuid=%s,wmNewsId=%d", uuid,wmNewsId));
        }
        log.info("自媒体文章的自动审核 完成...{},{},{},{}", uuid,p,o,wmNewsIdStr);
    }
}
